from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.contrib.auth.hashers import make_password,check_password
from ..models import Users
import random,time
import os
from django.core.paginator import Paginator

# Create your views here.
# 后台会员列表
def index(request):
    # 查询所有的会员数据
    data = Users.objects.all()
    # 分页类
    p = Paginator(data,5)
    inx_p = request.GET.get('page',1)
    # 获取当前页码数据
    userlist = p.get_page(inx_p)
    # 分配数据
    content = {'data':userlist,'contacts':userlist}
    # 加载模板
    return render(request,'myadmin/users/index.html',content)

# 添加会员列表
def add(request):
    return render(request,'myadmin/users/add.html')

# 执行会员添加
def insert(request):
    if request.method =='GET':
        return render(request,'myadmin/users/add.html')
    else:
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # return HttpResponse('接收表单提交的数据，进行数据的添加')

    # 密码加密
    # data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')

    try:
        # 上传头像
        file = request.FILES.get('pic',None)
        if file:
            data['face'] = imgupload(file)
        else:
            data.pop('pic')

        obj = Users(**data)
        obj.save()

        url = reverse('myadmin_users_index')
        return HttpResponse(f'<script>alert("会员添加成功"); location.href="{url}"</script>')
    except:
        url = reverse('myadmin_users_add')
        return HttpResponse(f'<script>alert("会员添加失败"); location.href="{url}"</script>')

# 执行会员删除
def delete(request):
    try:
        id = request.GET.get('id')
        obj = Users.objects.get(id=id)
        # 判断当前用户是否有上传头像
        try:
            if 'uploads' in obj.face:
                os.remove('.'+obj.face)
        except:
            return JsonResponse({'code':2,'msg':'头像删除失败'})
        obj.delete()
        return JsonResponse({'code':0,'msg':'删除成功'})
    except:
        return JsonResponse({'code':1,'msg':'删除失败'})


# 封装头像上传方法
def imgupload(file):
    try:
        filename = str(random.randint(10000,99999)+time.time())+'.'+file.name.split('.').pop()
        with open(f'./static/uploads/{filename}','wb+')as fp:
            fp.write(file.read())
        return f'/static/uploads/{filename}'
    except:
        return False